import { Component } from 'react'
import { View, Text } from '@tarojs/components'
import './ErrorBoundary.scss'

class ErrorBoundary extends Component {
  constructor(props) {
    super(props)
    this.state = { 
      hasError: false, 
      error: null,
      errorInfo: null 
    }
  }

  static getDerivedStateFromError(error) {
    // 更新状态，下次渲染时显示错误UI
    return { hasError: true, error }
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息
    this.setState({
      error,
      errorInfo
    })

    // 在生产环境中，可以将错误信息发送到错误报告服务
    if (process.env.NODE_ENV === 'production') {
      // 这里可以集成错误报告服务，如Sentry
      console.error('Error caught by boundary:', error, errorInfo)
    } else {
      console.error('Error caught by boundary:', error, errorInfo)
    }
  }

  handleRetry = () => {
    this.setState({ 
      hasError: false, 
      error: null, 
      errorInfo: null 
    })
  }

  handleReport = () => {
    // 这里可以实现错误报告功能
    console.log('Reporting error:', this.state.error)
  }

  render() {
    if (this.state.hasError) {
      // 自定义错误UI
      return (
        <View className='error-boundary'>
          <View className='error-icon'>⚠️</View>
          <Text className='error-title'>页面出现错误</Text>
          <Text className='error-message'>
            抱歉，页面加载时出现了问题
          </Text>
          
          {process.env.NODE_ENV === 'development' && this.state.error && (
            <View className='error-details'>
              <Text className='error-stack'>
                {this.state.error.toString()}
              </Text>
            </View>
          )}
          
          <View className='error-actions'>
            <View className='error-button primary' onClick={this.handleRetry}>
              <Text>重试</Text>
            </View>
            <View className='error-button secondary' onClick={this.handleReport}>
              <Text>报告问题</Text>
            </View>
          </View>
        </View>
      )
    }

    return this.props.children
  }
}

// 函数式组件的错误处理Hook
export const useErrorHandler = () => {
  const handleError = (error, errorInfo) => {
    if (process.env.NODE_ENV === 'development') {
      console.error('Error in component:', error, errorInfo)
    } else {
      // 生产环境错误处理
      console.error('Error in component:', error)
    }
  }

  const handleAsyncError = (asyncFn) => {
    return async (...args) => {
      try {
        return await asyncFn(...args)
      } catch (error) {
        handleError(error)
        throw error
      }
    }
  }

  return {
    handleError,
    handleAsyncError
  }
}

export default ErrorBoundary
